package com.dayu.finecomm.protocol.hd72;

import io.netty.buffer.ByteBuf;

import com.dayu.finecomm.protocol.codec.FixedLengthMagicDecoder;
import com.dayu.finecomm.protocol.codec.Protocol;
import com.dayu.finecomm.protocol.pojo.TPacket;
import com.dayu.finecomm.protocol.pojo.TPacket.VType;
import com.dayu.finecomm.protocol.pojo.TSensor;

@Protocol(XA5A5Decoder.PROTO)
public class XA5A5Decoder extends FixedLengthMagicDecoder<TPacket> {

	static final String PROTO = "HD72";

	public XA5A5Decoder() {

		super(new byte[] { (byte) 0xA5, (byte) 0xA5 },
				new byte[] { 0x0D, 0x0A }, 0, 2);
	}

	@Override
	public TPacket unpack(ByteBuf in) {

		in.skipBytes(2); // magic 0xA5A5
		in.skipBytes(2); // length

		int sn = in.readUnsignedShort();

		int func = in.readUnsignedByte();

		TPacket packet = new TPacket(VType.RRR, PROTO, sn,
				System.currentTimeMillis());

		switch (func) {

		case 0x81:

			int state = in.readUnsignedByte();

			packet.sensors.add(new TSensor("PID_NEW_STATE", state));

			break;

		case 0x82:

			state = in.readUnsignedByte();

			packet.sensors.add(new TSensor("PID_DELETE_STATE", state));
			break;

		case 0x88:

			state = in.readUnsignedByte();

			packet.sensors.add(new TSensor("PID_DELETE_ALL_STATE", state));
			break;

		case 0x83:

			in.skipBytes(6); // skip time

			int door = in.readUnsignedByte();
			state = in.readUnsignedByte();

			packet.sensors.add(new TSensor("DOOR_STATE", door));
			packet.sensors.add(new TSensor("KMFS", door == 1 ? 7 : 8));
			packet.sensors.add(new TSensor("DOOR_OPERATE_RESULT", state));

			break;

		case 0x84:

			in.skipBytes(6); // skip time
			int pid = in.readUnsignedShort();
			door = in.readUnsignedByte();

			packet.sensors.add(new TSensor("PID", pid));
			packet.sensors.add(new TSensor("DOOR_STATE", door));
			packet.sensors.add(new TSensor("KMFS", door == 1 ? 1 : 2));
			break;

		case 0x87:

			in.skipBytes(6); // skip time
			door = in.readUnsignedByte();

			packet.sensors.add(new TSensor("SERIAL_NUMBER", in
					.readUnsignedInt()));
			packet.sensors.add(new TSensor("DOOR_STATE", door));
			packet.sensors.add(new TSensor("KMFS", door == 1 ? 3 : 4));
			break;

		case 0x85:

			in.skipBytes(6); // skip time
			pid = in.readUnsignedShort();
			door = in.readUnsignedByte();

			packet.sensors.add(new TSensor("PID", pid));
			packet.sensors.add(new TSensor("DOOR_STATE", door));
			packet.sensors.add(new TSensor("KMFS", door == 1 ? 5 : 6));
			break;

		default:
			break;
		}

		return packet;
	}

	@Override
	public byte[] echo() {
		return "@222".getBytes();
	}
}
